package com.jec.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.Reader;
import java.io.Writer;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.core.util.QuickWriter;
import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
import com.thoughtworks.xstream.io.xml.PrettyPrintWriter;
import com.thoughtworks.xstream.io.xml.XppDriver;

/**
 * Created by jeremyliu on 5/23/16.
 */
public class XmlUtils {


    private static XStream xstream = new XStream(new XppDriver() {
        @Override
        public HierarchicalStreamWriter createWriter(Writer out) {
            return new PrettyPrintWriter(out) {
                // 对所有xml节点的转换都增加CDATA标记
                boolean cdata = true;

                @Override
                @SuppressWarnings("rawtypes")
                public void startNode(String name, Class clazz) {
                    super.startNode(name, clazz);
                }

                @Override
                protected void writeText(QuickWriter writer, String text) {
                    if (cdata) {
                        writer.write("<![CDATA[");
                        writer.write(text);
                        writer.write("]]>");
                    } else {
                        writer.write(text);
                    }
                }
            };
        }
    });

    public static String objToXml(Object obj, Class<?>... classes){
        xstream.processAnnotations(classes);
        return xstream.toXML(obj);
    }

    public static Object toEntity(String xml, Class<?>... clazz){
        xstream.setMode(XStream.NO_REFERENCES);
        xstream.processAnnotations(clazz);
        return xstream.fromXML(xml);
    }

    public static boolean writeXml(String filepath,Object obj, Class<?>... classes){
        Writer out;
        try {
            out = new FileWriter(new File(filepath));
            out.write(objToXml(obj,classes));
            out.close();
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
        return true;
    }

    @SuppressWarnings("unchecked")
	public static<T> T readXml(String filepath, Class<?>... classes){
        Reader in;
        try {
            in = new FileReader(new File(filepath));
            BufferedReader reader = new BufferedReader(in);
            String line = reader.readLine();
            String xml = "";
            while(line != null){
                xml += line;
                line = reader.readLine();
            }
            in.close();
            return (T)toEntity(xml,classes);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
